﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Configuration.Install;
using System.Linq;
using System.Reflection;
using NLog;
using DeSleeper.Service;

namespace DeSleeper.ServiceHost
{
    [RunInstaller(true)]
    public partial class ProjectInstaller : Installer
    {
    	private static readonly Logger _logger = LogManager.GetCurrentClassLogger();

        public ProjectInstaller()
        {
            InitializeComponent();
        }

        private void ProjectInstaller_BeforeInstall(object sender, InstallEventArgs e)
        {
            var config = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
            var builder = new ConfigurationBuilder(config);
            Uri localAddress = null;
            if (Context.Parameters.ContainsKey("LocalAddress"))
				if (!Uri.TryCreate(Context.Parameters["LocalAddress"], UriKind.Absolute, out localAddress))
					_logger.Warn("Local Address [{0}] was not valid, installing with default address.", Context.Parameters["LocalAddress"]);
			
			builder.SetupWakeUpService(localAddress);

			if (Context.Parameters.ContainsKey("PeerAddress"))
        	{
				Uri peerAddress;
				if (!Uri.TryCreate(Context.Parameters["PeerAddress"], UriKind.Absolute, out peerAddress))
					_logger.Warn("Peer Address [{0}] was not valid, installing with default address.", Context.Parameters["PeerAddress"]);

        		builder.SetupPeerService(peerAddress);
        	}

        	builder.Save();
        }
    }
}
